﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Aspose.Words;
using DevExpress.Mvvm.Native;
using DevExpress.Xpf.RichEdit;
using DevExpress.XtraRichEdit;
//using Microsoft.Office.Core;
using SaveFileDialog = Microsoft.Win32.SaveFileDialog;
using Shape = Aspose.Words.Drawing.Shape;

namespace DGIS.Word.WPF.ICommand
{
    public class SaveCommand : System.Windows.Input.ICommand
    {
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            RichEditControl richEditControl = parameter as RichEditControl;

            SaveFileDialog dlg = new SaveFileDialog()
            {
                Filter = "docx|*.docx"
            };
            if (dlg.ShowDialog() == true)
            {
                string savePath = dlg.FileName;
                richEditControl.SaveDocument(savePath, DocumentFormat.OpenXml);

                ConvertDoc(savePath);

                MessageBox.Show("保存成功");
            }
        }

        private bool ConvertDoc(string docPath)
        {
            //try
            //{
            //    var wordApp = new Microsoft.Office.Interop.Word.ApplicationClass(); //初始化
            //    Object Nothing = Missing.Value;
            //    object fileName = docPath;
            //    var wordDoc1 = wordApp.Documents.Open(ref fileName, ref Nothing, ref Nothing);

            //    foreach (Microsoft.Office.Interop.Word.Shape shape in wordDoc1.Shapes)
            //    {
            //        if (shape.Name == "penLink")
            //        {
            //            shape.WrapFormat.AllowOverlap = -1;
            //        }
            //    }
            //    wordDoc1.Close();
            //    wordDoc1.Save();

            //    return true;
            //}
            //catch (Exception ex)
            //{
            //    return false;
            //}

            try
            {
                Document doc = new Document(docPath);
                var nodes = doc.GetChildNodes(NodeType.Shape, true);
                foreach (Node node in nodes)
                {
                    if (node.NodeType == NodeType.Shape)
                    {
                        Shape shape = node as Shape;
                        if (shape.Name == "penLink")
                        {
                            shape.AllowOverlap = true;
                        }
                    }
                }
                doc.Save(docPath, SaveFormat.Docx);

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            
        }
    }
}
